//
//  BHMyCompetitionDetailViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/18.
//

import UIKit

class BHMyCompetitionDetailViewController: BHBaseViewController {

    lazy var navigationBar: BHApplyDetailNavigationBar = {
        let view = BHApplyDetailNavigationBar.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.begainY)
        view.delegate = self
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.delegate = self
        view.dataSource = self
        view.isHidden = false
        return view
    }()
    
    var applyId: String = ""
    
    fileprivate var model = BHUserGameApplyDetailModel.init()
    // 是否是团队报名，默认个人
    fileprivate var teamType: Bool = false
    
    fileprivate var openFlag: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.removeFromSuperview()
        self.view.addSubview(self.navigationBar)
        
        self.regiseterCell()
        self.view.addSubview(self.tableView)
        
        self.queryApplyDetailService()
    }
    
}

extension BHMyCompetitionDetailViewController {
    private func regiseterCell() {
        
        self.tableView.regiseterNib(nibName: "BHApplyDetailInfoCell")
        self.tableView.regiseterNib(nibName: "BHApplyDetailTipTableViewCell")
        self.tableView.regiseterNib(nibName: "BHApplyDetailTeamCell")
        self.tableView.regiseterNib(nibName: "BHApplyStepTableViewCell")
        self.tableView.regiseterNib(nibName: "BHApplyOrderInfoCell")
    }
}

extension BHMyCompetitionDetailViewController : BHApplyDetailNavigationBarDelegate {
    func applyNavigationDidActFunction(type: Int) {
        if type == 0 {
            self.navigationController?.popViewController(animated: true)
        }
        if type == 1 { // 赛事详情
            BHRouter.shared.bh_goGameDetail(gameId: self.model.eventId)
        }
        if type == 2 { // 退赛
            BHCommonTool.showCustomAlertWith(showVC: self, title: "确定要退出比赛吗", message: "赛事报名已经结束了，现在退出将\n不返相关费用～", okBtn: "我在想想", cancel: "现在退出") { (stay) in
                if stay == false {
                    if self.model.ifCaptain == 1  { // 队长，解散战队
                        if self.model.eventType == 2 {
                            self.captainDissolveGameService()
                        }else {
                            self.teamUserQuiteGameService()
                        }
                    }else {
                        self.teamUserQuiteGameService()
                    }
                }
            }
        }
    }
}

extension BHMyCompetitionDetailViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.teamType == true {
            return 5
        }
        return 4
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            if self.model.eventType == 2 { // 团体赛
                if self.openFlag == true {
                    return self.model.members.count
                }else {
                    return 1
                }
            }
            return self.model.members.count
        }
        if section == 1 {
            return 1
        }
        if section == 2 {
            if self.teamType == true {
                return 1
            }else {
             
                return 5  // 比赛进程
            }
        }
        if section == 3 { //
            if self.teamType == true {
                return 5  // 比赛进程
            }
            return 1
        }
        if section == 4 { // 只有团队报名才有4
            return 1
        }
        return 0
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if self.model.members.count == 0 {
                return 0
            }
            let model = self.model.members[indexPath.row]
            return BHApplyDetailInfoCell.infoHeight(count: model.allCustomDic.count)
        }
        if indexPath.section == 1 {
            return 54
        }
        if indexPath.section == 2 {
            if self.teamType == true {
                return BHApplyDetailTeamCell.heightWithWait
            }else {
                if indexPath.row == 2 { // 签到
                    if self.model.signinStartTime.isEmpty == true { // 签到时间
                        return 0
                    }
                    return 100
                }else {
                    return 60
                }
            }
        }
        if indexPath.section == 3 {
            if self.teamType == true {
                if indexPath.row == 2 { // 签到
                    if self.model.signinStartTime.isEmpty == true { // 签到时间
                        return 0
                    }
                    return 100
                }else {
                    return 60
                }
            }else { // 订单（个人）
                if self.model.fee.isEmpty == true ||
                    self.model.fee == "0" ||
                    self.model.fee == "0.0" ||
                    self.model.fee == "0.00" {
                    return 0
                }else {
                    return 120
                }
            }
        }
        if indexPath.section == 4 { // 订单（团队）
            if self.model.fee.isEmpty == true ||
                self.model.fee == "0" ||
                self.model.fee == "0.0" ||
                self.model.fee == "0.00" {
                return 0
            }else {
                return 120
            }
        }
       return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 || section == 1 {
            return 40
        }
        if section == 2 {
            if self.teamType == true {
                return 40
            }
            return CGFloat.leastNormalMagnitude
        }
        if section == 3 {
            if self.teamType == true {
                return CGFloat.leastNormalMagnitude
            }
            return 10
        }
        if section == 4 {
            return 10
        }
        return CGFloat.leastNormalMagnitude
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if self.teamType == true { // 团体赛
            if section == 0 {
                if self.model.members.count > 1 {
                    return 45
                }
            }
        }
        return CGFloat.leastNormalMagnitude
    }
    
}

extension BHMyCompetitionDetailViewController: UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 || section == 1 {
            let view = BHApplyDetailSecView.loadFromXib()
            view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 40)
            view.sec_name_label.text = section == 0 ? "报名信息":"报名费："
            view.money_label.isHidden = section == 0
            if self.model.eventType == 2 && self.model.ifCaptain == 1 { // 团体赛，是队长
                if section == 0 {
                    view.rightBtn.isHidden = self.model.ifQuit == 1
                    view.rightBtn.addBtnAction(action: {[weak self] (_) in
                        if self?.model.reminder == 0 { // 人数满了
                            BHToast.toast(text: "当前团队人数已满")
                            return
                        }
                        let infoEditeVC = BHApplyUserInfoEditeViewController.init()
                        infoEditeVC.editeType = 2
                        infoEditeVC.appendUserInfoModel = self?.model ?? BHUserGameApplyDetailModel.init()
                        self?.navigationController?.pushViewController(infoEditeVC, animated: true)
                        infoEditeVC.refreshDetailInfoBlock = { [weak self] in
                            self?.queryApplyDetailService()
                        }
                    }, for: .touchUpInside)
                }else {
                    view.rightBtn.isHidden = true
                }
            }else {
                view.rightBtn.isHidden = true
            }
            if self.model.fee.isEmpty == true ||
                self.model.fee == "0" ||
                self.model.fee == "0.0" ||
                self.model.fee == "0.00" {
                view.money_label.text = "无需报名费"
            }else {
                view.money_label.text = "¥\(self.model.fee)"
            }
            return view
        }
        if section == 2 {
            if self.teamType == true {
                let view = BHApplyDetailSecView.loadFromXib()
                view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 40)
                view.sec_name_label.text = "所属战队"
                view.money_label.isHidden = true
                return view
            }
            return nil
        }
        if section == 3 {
            if self.teamType == true {
                return nil
            }
            let view = UIView.init()
            view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 10)
            view.backgroundColor = .color_f8f8f8
            return view
        }
        if section == 4 {
          
            let view = UIView.init()
            view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 10)
            view.backgroundColor = .color_f8f8f8
            return view
        }
        
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if self.teamType == true { // 团体赛
            if section == 0 {
                if self.model.members.count > 1 {
                    let view = BHApplyDetailFlagMoreView.loadFromXib()
                    view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 45)
                    view.openFlagBtn.isSelected = self.openFlag
                    view.openFlagBtn.addBtnAction(action: {[unowned self] (_) in
                        self.openFlag = !self.openFlag
                        tableView.reloadData()
                    }, for: .touchUpInside)
                    return view
                }
            }
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyDetailInfoCell", for: indexPath) as! BHApplyDetailInfoCell
            let model = self.model.members[indexPath.row]
            cell.model = model
            return cell
        }
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyDetailTipTableViewCell", for: indexPath) as! BHApplyDetailTipTableViewCell
            return cell
        }
        if indexPath.section == 2 {
            if self.teamType == true {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyDetailTeamCell", for: indexPath) as! BHApplyDetailTeamCell
                cell.team_name_label.text = self.model.teamName
                cell.team_count_label.text = "战队人数：\(self.model.memberNumber)人"
                if self.model.reminder != 0 { // 不满足人数
                    cell.teamAddition_label.setTitle(" 还差\(self.model.reminder)人即可报名成功", for: .normal)
                }else {
                    cell.teamAddition_label.setTitle(" 已达到参赛报名人数要求，报名成功", for: .normal)
                }
                return cell
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyStepTableViewCell", for: indexPath) as! BHApplyStepTableViewCell
            self.configTime(indexPath: indexPath, cell: cell)
            return cell
        }
        if indexPath.section == 3 {
            if self.teamType == true {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyStepTableViewCell", for: indexPath) as! BHApplyStepTableViewCell
                self.configTime(indexPath: indexPath, cell: cell)
                return cell
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyOrderInfoCell", for: indexPath) as! BHApplyOrderInfoCell
            cell.order_label.text = "订单编号：\(self.model.code)"
            cell.pay_time_label.text = "支付时间：\(self.model.payTime)"
            return cell
        }
        if indexPath.section == 4 {
          
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyOrderInfoCell", for: indexPath) as! BHApplyOrderInfoCell
            return cell
        }
        return UITableViewCell()
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let model = self.model.members[indexPath.row]
            let infoEditeVC = BHApplyUserInfoEditeViewController.init()
            infoEditeVC.model = model
            if self.model.ifQuit == 1 {
                infoEditeVC.canEdite = false
            }else {
                infoEditeVC.canEdite = self.model.ifCaptain == 1
            }
            self.navigationController?.pushViewController(infoEditeVC, animated: true)
            infoEditeVC.refreshDetailInfoBlock = { [weak self] in
                self?.queryApplyDetailService()
            }
        }
        if indexPath.section == 2 {
            if self.teamType == true {
                if indexPath.row == 0 {
                    let teamVC = BHApplyTeamUserViewController.init()
                    teamVC.teamModel = self.model
                    teamVC.applyId = self.applyId
                    self.navigationController?.pushViewController(teamVC, animated: true)
                    
                }
            }
        }
    }
}

extension  BHMyCompetitionDetailViewController {
    func configTime(indexPath: IndexPath,cell: BHApplyStepTableViewCell) {
        cell.stepType = indexPath.row
        cell.signType = self.model.ifSignin == 1
        if indexPath.row == 0 {
            cell.time_label.text = self.model.signupTime
        }
        if indexPath.row == 1 {
            cell.time_label.text = self.model.signupEnd
        }
        if indexPath.row == 2 {
            cell.time_label.text = self.model.signinStartTime
        }
        if indexPath.row == 3 {
            cell.time_label.text = self.model.startTime
        }
        if indexPath.row == 4 {
            cell.time_label.text = self.model.endTime
        }
    }
}

extension BHMyCompetitionDetailViewController {
    func queryApplyDetailService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.me_myGame_applyDetail_url, paramters: ["id":self.applyId]) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                self.tableView.isHidden = false
                let resultDic = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                self.model.parseDic(resultDic)
                self.teamType = self.model.eventType == 2
                self.tableView.reloadData()
                if self.model.ifCaptain == 1  &&
                    self.model.eventType == 2{ // 如果是队长
                    self.navigationBar.quiteBtn.setTitle("解散战队", for: .normal)
                }
                self.navigationBar.quiteBtn.isHidden = self.model.ifQuit == 1
                
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
  
}

// MARK: 队长解散赛事
extension BHMyCompetitionDetailViewController {
    func captainDissolveGameService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.post(url: String.me_myGame_dissolveGame_url, paramters: ["id":self.applyId]) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "赛事已解散")
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
               
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}

// MARK: 队员退出比赛
extension BHMyCompetitionDetailViewController {
    func teamUserQuiteGameService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.post(url: String.me_myGame_quiteGame_url, paramters: ["id":self.applyId]) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "已退出赛事")
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
               
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}
